package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.UserRelation;
import org.aeon.entity.dto.UserDto;
import org.aeon.message.request.FriendDeleteRequestMessage;
import org.aeon.message.response.FriendDeleteResponseMessage;
import org.aeon.service.UserRelationService;
import org.aeon.service.factory.UserRelationServiceFactory;
import org.aeon.service.factory.UserServiceFactory;

/**
 * @author: MissingAeon
 * @date: 2024/1/30 10:04
 * @description: 好友删除请求处理程序
 */
@Slf4j
@ChannelHandler.Sharable
public class FriendDeleteRequestHandler extends SimpleChannelInboundHandler<FriendDeleteRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FriendDeleteRequestMessage msg) throws Exception {
        final FriendDeleteResponseMessage resMsg = new FriendDeleteResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final UserRelationService service = UserRelationServiceFactory.getService();
        final UserRelation userRelation = service.queryRelation(msg.getUserId(), msg.getUserId2());
        if (userRelation == null || !userRelation.getIsFriend()) {
            resMsg.setResponse(false, "你们还不是好友关系");
        } else {
            final boolean disassociate = service.disassociate(msg.getUserId(), msg.getUserId2());
            if (disassociate) {
                final UserDto userInfo = UserServiceFactory.getService().getSimpleUser(msg.getUserId2());
                resMsg.setResponse(true, userInfo.getNickname() + "好友移除");
            } else resMsg.setResponse(false, "好友移除失败");
        }

        ctx.writeAndFlush(resMsg);
    }
}
